#include "t_box_video_reply.h"

#include "xmlutil.h"

/*
http://code.google.com/p/get-flash-videos/source/browse/trunk/FlashVideo/Site/Youtube.pm?r=311
my @formats = (
  { id => 37, resolution => [1920, 1080] },
  { id => 22, resolution => [1280, 720] },
  { id => 35, resolution => [854, 480] },
  { id => 34, resolution => [640, 360] },
  { id => 18, resolution => [480, 270] },
  { id => 5,  resolution => [400, 224] },
  { id => 17, resolution => [176, 144] },
  { id => 13, resolution => [176, 144] },
);
*/

T_Box_Video_Reply::T_Box_Video_Reply(T_Box_Downloader *a_parent, QString a_id) :
    QObject(a_parent), f_id(a_id), f_title(""), f_view_count(0)
{
    f_parent = a_parent;
    QNetworkAccessManager *v_nam = a_parent->getNAM();
    //[f_reply_0]
    QString v_url_str = QString("http://gdata.youtube.com/feeds/api/videos/%1").arg(a_id);
    QUrl v_url(v_url_str);
    QNetworkRequest v_request(v_url);
    f_reply_0 = v_nam->get(v_request);
    connect(f_reply_0, SIGNAL(finished()), this, SLOT(self_on_reply_finished()));
    //[f_reply_1]
    QString v_url_1 =
            QString("http://www.youtube.com/get_video_info?&video_id=%1&el=embedded&ps=default")
            .arg(a_id);
    v_request.setUrl(v_url_1);
    f_reply_1 = v_nam->get(v_request);
    connect(f_reply_1, SIGNAL(finished()), this, SLOT(self_on_reply_finished()));
    //[f_reply_2]
    QString v_watch_url =
            QString("http://www.youtube.com/watch?v=%1")
            .arg(a_id);
    v_request.setUrl(v_watch_url);
    f_reply_2 = v_nam->get(v_request);
    connect(f_reply_2, SIGNAL(finished()), this, SLOT(self_on_reply_finished()));

}

void T_Box_Video_Reply::self_emit_finished()
{
    emit finished();
}

void T_Box_Video_Reply::self_on_reply_finished()
{
    ////QNetworkReply *v_reply = (QNetworkReply *)sender();

    if(!f_reply_0->isFinished()) return;
    if(!f_reply_1->isFinished()) return;
    if(!f_reply_2->isFinished()) return;

    //[f_reply_0]
    {
        QByteArray v_xml = f_reply_0->readAll();
        XmlUtil::backupXmlBody(v_xml, "self_on_reply_finished");
        QDomDocument domDocument;
        if(XmlUtil::setXmlContent(domDocument, v_xml))
        {
            QDomElement v_entry = domDocument.documentElement();
            // [/entry/yt:statistics(viewCount)]
            QDomNodeList v_stat_list = v_entry.elementsByTagNameNS("http://gdata.youtube.com/schemas/2007", "statistics");
            QDomElement v_stat_elem = v_stat_list.at(0).toElement();
            f_view_count = v_stat_elem.attribute("viewCount").toLongLong();
            qDebug() << "[T_Box_Video_Reply::self_on_reply_finished()] f_view_count" << f_view_count;
            // [/entry/title]
            QDomNodeList v_title_list = v_entry.elementsByTagNameNS("http://www.w3.org/2005/Atom", "title");
            QDomElement v_title_elem = v_title_list.at(0).toElement();
            f_title = v_title_elem.text();
            qDebug() << "[T_Box_Video_Reply::self_on_reply_finished()] f_title" << f_title;
        }
    }
    f_token = "";
    //[f_reply_1]
    {
        QByteArray v_params_1 = f_reply_1->readAll();
        v_params_1.prepend("?");
        QUrl v_params_2;
        v_params_2.setEncodedUrl(v_params_1);
        QString v_status = v_params_2.queryItemValue("status");
        QString v_reason = v_params_2.queryItemValue("reason");
        f_token = v_params_2.queryItemValue("token");
        QString v_allow_embed = v_params_2.queryItemValue("allow_embed");
        QString v_fmt_stream_map = v_params_2.queryItemValue("fmt_stream_map");
        //qDebug() << v_status << v_allow_embed << v_token << v_fmt_stream_map;
        if(v_status == "fail")
        {
            //g_Env->showMessage(v_reason);
        }
        else
        {
            //g_Env->showMessage("");
        }
        if(f_token == "")
        {
            qDebug() << v_params_2;
        }
        f_fmt_map.clear();
        if(v_fmt_stream_map != "")
        {
            QStringList v_slist_1 = v_fmt_stream_map.split(',');
            for(int i=0; i<v_slist_1.size(); i++)
            {
                QStringList v_slist_2 = v_slist_1.at(i).split('|');
                int v_fmt = v_slist_2.at(0).toInt();
                QString v_stream_url_1 = v_slist_2.at(1);
                QUrl v_stream_url_2;
                v_stream_url_2.setEncodedUrl(v_stream_url_1.toLatin1());
                f_fmt_map.insert(v_fmt, v_stream_url_2);
            }
        }
        qDebug() << "[v_token(embed)]" << f_token;
        qDebug() << "[a_fmt_map.keys()]" << f_fmt_map.keys();
    }
    //[f_reply_2]
    if(f_token.isEmpty())
    {
        QByteArray v_html_raw = f_reply_2->readAll();
        //qDebug() << "[v_html_raw]" << v_html_raw;
        qDebug() << "[v_html_raw.size()]" << v_html_raw.size();
        QString v_html_str = QString::fromUtf8(v_html_raw);
        //qDebug() << "[v_html_str]" << v_html_str;

        int v_pos = 0;

        QRegExp v_rxStream("[?&](fmt_stream_map=[^&'\"\\\\]+)");
        v_pos = v_rxStream.indexIn(v_html_str, 0);
        f_fmt_map.clear();
        if(v_pos != -1)
        {
            QByteArray v_params_raw = v_rxStream.cap(1).toLatin1();
            v_params_raw.prepend("?");
            QUrl v_params_url;
            v_params_url.setEncodedUrl(v_params_raw);
            QString v_fmt_stream_map = v_params_url.queryItemValue("fmt_stream_map");
            if(v_fmt_stream_map != "")
            {
                QStringList v_slist_1 = v_fmt_stream_map.split(',');
                for(int i=0; i<v_slist_1.size(); i++)
                {
                    QStringList v_slist_2 = v_slist_1.at(i).split('|');
                    int v_fmt = v_slist_2.at(0).toInt();
                    QString v_stream_url_1 = v_slist_2.at(1);
                    QUrl v_stream_url_2;
                    v_stream_url_2.setEncodedUrl(v_stream_url_1.toLatin1());
                    f_fmt_map.insert(v_fmt, v_stream_url_2);
                }
            }
        }
        QRegExp v_rxToken("[?&](t=[^&'\"\\\\]+)");
        v_pos = v_rxToken.indexIn(v_html_str, 0);
        qDebug() << "[pos]" << v_pos;
        if(v_pos == -1)
        {
            f_token = "";
        }
        else
        {
            QByteArray v_params_raw = v_rxToken.cap(1).toLatin1();
            v_params_raw.prepend("?");
            QUrl v_params_url;
            v_params_url.setEncodedUrl(v_params_raw);
            f_token = v_params_url.queryItemValue("t");
        }
        qDebug() << "[v_token(detail)]" << f_token;
        qDebug() << "[a_fmt_map.keys()]" << f_fmt_map.keys();
    }


    QMetaObject::invokeMethod(this, "self_emit_finished", Qt::QueuedConnection);
}
